﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using TanmiaGrp.Basis;
using TanmiaGrp.Basis.Specification;
using TanmiaGrp.GeneralLedger.Core;
using TanmiaGrp.GeneralLedger.IRepository;
using TanmiaGrp.GeneralLedger.IRepository.Basis;

namespace TanmiaGrp.GeneralLedger.Domain
{
    public class GroupDomain : BaseDomain<Group, GroupDomain>
    {
        public override List<Group> GetPage(int pageIndex)
        {
            if (pageIndex < 0 || pageIndex > GetPageCount())
                throw new ArgumentOutOfRangeException("pageIndex", "دليل صفحة المجموعات خارج المجال");

            return QueryRepository.LoadAll(new GenericSpecification<Group>(pageIndex, ConfigManager.Obj.PageSize), x => x.GroupID);
        }

        public override List<Group> SearchPage(SearchSpecification searchSpecs)
        {
            Contract.Assert(searchSpecs != null, "searchSpecs must not be null.");

            return QueryRepository.LoadAll(CreateSpecification(searchSpecs), order => order.GroupName);
        }

        public List<Group> GetPages()
        {
            
            return QueryRepository.LoadAll<Group, string>(new GenericSpecification<Group>(), o => o.GroupName);
        }

        private GenericSpecification<Group> CreateSpecification(SearchSpecification searchSpecs)
        {
            Expression<Func<Group, bool>> predicate = x => searchSpecs.ShowIsDisabled ? true : x.IsEnabled == true;

            // InteractiveSearch and Show IsEnabled = true
            if (!string.IsNullOrEmpty(searchSpecs.InteractiveSearch) )
                predicate = x => (searchSpecs.ShowIsDisabled ? true : x.IsEnabled == true) && (x.GroupName.Contains(searchSpecs.InteractiveSearch) ||
                                 x.Notes.Contains(searchSpecs.InteractiveSearch) ||
                                 x.CreateDate.ToString().Contains(searchSpecs.InteractiveSearch));

            return new GenericSpecification<Group>(
                pageIndex: searchSpecs.PageIndex,
                pageSize: ConfigManager.Obj.PageSize,
                predicate: predicate);
        }
    }
}
